package com.sx.user.service.impl;

import com.sx.user.dao.TokenRepository;
import com.sx.user.dao.UserRepository;
import com.sx.user.entity.Token;
import com.sx.user.entity.User;
import com.sx.user.service.RegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author shengx
 * @date 2020/5/14 21:48
 */
@Service
public class RegisterServiceImpl implements RegisterService {

    @Autowired
    private TokenRepository tokenRepository;

    @Autowired
    private UserRepository userRepository;

    @Override
    public int register(String email, String password) {
        User user = new User();
        user.setEmail(email);
        user.setPassword(password);
        User save = userRepository.save(user);
        return save.getId();
    }

    @Override
    public Boolean isRegister(String email) {
        User user = userRepository.findByEmail(email);
        return user == null ? false : true;
    }

    @Override
    public Token getEmailByToken(String token) {
        List<Token> tokens = tokenRepository.findByToken(token);
        if(tokens!=null){
            return tokens.get(0);
        }
        return null;
    }

    @Override
    public Token addToken(String email, String token) {
        Token myToken = new Token();
        myToken.setEmail(email);
        myToken.setToken(token);
        Token save = tokenRepository.save(myToken);
        return save;
    }

    @Override
    public User signIn(String email, String password) {
        User u = userRepository.findByEmail(email);
        if (u != null && u.getPassword().equals(password)) {
            return u;
        }
        return null;
    }

}
